'use strict';

const Service = require('egg').Service;
const random = require('random');

const randNum = random.int(100000, 999999);

class UserTelLoginService extends Service {
  async telLogin(telInfo) {
    const { ctx } = this;
    const user = await ctx.model.User.findOne({
      where: {
        tel: telInfo.phone,
      },
    });
    if (user) {
      const Num = await this.app.redis.get('telcode');
      if (Num === telInfo.Code) {
        const tokenID = ctx.getToken({
          id: user.dataValues.id,
          contact: user.dataValues.tel,
        }, {
          expiresIn: '3day',
        });
        await this.app.redis.setex(user.dataValues.id, 60 * 30, tokenID);
        await this.app.redis.setex(user.dataValues.id + 'u', 60 * 30, JSON.stringify(user.dataValues));
        ctx.body = {
          status: 200,
          msg: '登录成功',
          tokenID,
        };
      } else {
        ctx.body = {
          status: 400,
          msg: '验证码错误，请重新输入',
        };
      }
    }
  }
  async monitorTel(tel) {
    const { ctx, app } = this;
    if (tel) {
      const user = await ctx.model.User.findOne({
        where: {
          tel,
        },
      });
      if (!user) {
        ctx.body = {
          state: 400,
          msg: '此手机号没有注册，请注册后重试',
        };
        return;
      }
      app.redis.setex('telcode', 60, randNum);
      ctx.body = {
        status: 200,
        randNum,
        msg: '发送短信成功',
      };
      // ctx.helper.sendCode(tel, randNum);
      // if (result.error_code === 0) {
      //   app.redis.setex('telcode', 60, randNum);
      //   ctx.body = {
      //     status: 200,
      //     msg: '发送短信成功',
      //   };
      // }
    }
  }
}

module.exports = UserTelLoginService;
